﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPITest.Filter
{
    public class GlobalExceptionFilter: IExceptionFilter
    {
        //public void OnException(ExceptionContext context)
        //{
        //    Exception ex = context.Exception;
        //    string errMsg = "GlobalExceptionFilter-OnException：" + ex.Message;
        //    //记录获取到的异常信息
        //}
        private readonly ILogger<GlobalExceptionFilter> _logger;
        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            var operation = context.HttpContext.Request.RouteValues["controller"] + "/" + context.HttpContext.Request.RouteValues["action"];

            _logger.LogError(context.Exception, $"{operation}  Exception:" + context.Exception.Message); //记录错误日志
                                                                                                         //拦截处理
            if (!context.ExceptionHandled) {
                context.Result = new JsonResult(new {
                    status = false,
                    msg = "系统内部错误:" + context.Exception.Message
                });
                context.ExceptionHandled = true;
            }
        }
    }
}
